<template>
  <!-- 导航栏 -->
  <Navbar />
  
  <div class="order-detail-container">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-left">
          <button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回订单列表
          </button>
        </div>
        <h2>
          <el-icon><Document /></el-icon>
          订单详情
        </h2>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-section">
        <div class="loading-spinner">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
      </div>

      <!-- 订单不存在 -->
      <div v-else-if="!order" class="empty-state">
        <div class="empty-icon">
          <el-icon><Warning /></el-icon>
        </div>
        <h3>订单不存在</h3>
        <p>抱歉，未找到该订单信息</p>
        <button @click="goBack" class="btn btn-primary">
          <el-icon><ArrowLeft /></el-icon>
          返回订单列表
        </button>
      </div>

      <!-- 订单详情内容 -->
      <div v-else class="order-detail-content">
        <!-- 订单基本信息 -->
        <div class="order-info-card">
          <div class="card-header">
            <h3>
              <el-icon><InfoFilled /></el-icon>
              订单信息
            </h3>
            <div class="order-status">
              <span :class="['status-badge', getStatusClass(order.orderStatus)]">
                {{ getStatusText(order.orderStatus) }}
              </span>
            </div>
          </div>
          <div class="card-content">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">订单编号</span>
                <span class="value">{{ order.orderId }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间</span>
                <span class="value">{{ formatDate(order.purchaseTime || order.orderDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付方式</span>
                <span class="value">{{ order.paymentMethod || '在线支付' }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单总额</span>
                <span class="value price">¥{{ order.totalAmount || '0.00' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="shipping-info-card">
          <div class="card-header">
            <h3>
              <el-icon><Van /></el-icon>
              收货信息
            </h3>
          </div>
          <div class="card-content">
            <div class="shipping-details">
                             <div class="recipient-info">
                 <div class="recipient-name">
                   <el-icon><User /></el-icon>
                   <span>{{ order.receiverName || '收货人' }}</span>
                 </div>
                 <div class="recipient-phone">
                   <el-icon><Phone /></el-icon>
                   <span>{{ order.receiverPhone || order.contactInfo || '联系电话' }}</span>
                 </div>
               </div>
               <div class="shipping-address">
                 <el-icon><Location /></el-icon>
                 <span>{{ order.shippingAddress || '收货地址' }}</span>
               </div>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="products-card">
          <div class="card-header">
            <h3>
              <el-icon><Box /></el-icon>
              商品信息
            </h3>
          </div>
          <div class="card-content">
            <div class="products-list">
              <div 
                v-for="item in orderDetails" 
                :key="item.orderDetailId || item.productId"
                class="product-item"
              >
                <div class="product-image">
                  <img 
                    v-if="item.productImage && item.productImage !== '/placeholder-product.png'" 
                    :src="item.productImage" 
                    :alt="item.productName"
                    @error="handleImageError"
                  />
                                     <div v-else class="default-product-icon">
                     <el-icon><Cpu /></el-icon>
                   </div>
                </div>
                <div class="product-info">
                  <h4>{{ item.productName || '商品名称' }}</h4>
                  <p v-if="item.specParams">{{ item.specParams }}</p>
                  <div class="product-meta">
                    <span class="price">¥{{ item.unitPrice || item.price || '0.00' }}</span>
                    <span class="quantity">x{{ item.quantity || 1 }}</span>
                    <span class="subtotal">小计: ¥{{ ((item.unitPrice || item.price || 0) * (item.quantity || 1)).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions-card">
          <div class="card-header">
            <h3>
              <el-icon><Setting /></el-icon>
              订单操作
            </h3>
          </div>
          <div class="card-content">
            <div class="actions-list">
                             <button 
                 v-if="order.orderStatus === 'PENDING'"
                 @click="payOrder"
                 class="btn btn-primary"
               >
                 <el-icon><CreditCard /></el-icon>
                 立即支付
               </button>
               <button 
                 v-if="order.orderStatus === 'SHIPPED'"
                 @click="confirmReceived"
                 class="btn btn-success"
               >
                 <el-icon><Check /></el-icon>
                 确认收货
               </button>
               <button 
                 v-if="['PENDING', 'PAID'].includes(order.orderStatus)"
                 @click="cancelOrder"
                 class="btn btn-danger"
               >
                 <el-icon><Close /></el-icon>
                 取消订单
               </button>
               <button 
                 @click="contactService"
                 class="btn btn-secondary"
               >
                 <el-icon><Service /></el-icon>
                 联系客服
               </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Document, Loading, Warning, InfoFilled, Van, Box, Setting, CreditCard, Check, Close, Service, User, Phone, Location, Cpu } from '@element-plus/icons-vue'
import { orderAPI } from '@/api'
import Navbar from '@/components/Navbar.vue'
import { message, confirm, feedback, showCustomerService } from '@/utils/message'

export default {
  name: 'OrderDetailView',
  components: {
    Navbar,
    ArrowLeft,
    Document,
    Loading,
    Warning,
    InfoFilled,
    Van,
    Box,
    Setting,
    CreditCard,
    Check,
    Close,
    Service,
    User,
    Phone,
    Location,
    Cpu
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const loading = ref(false)
    const order = ref(null)
    const orderDetails = ref([])
    
    const orderId = computed(() => route.params.id)
    
    const fetchOrderDetail = async () => {
      try {
        loading.value = true
        const response = await orderAPI.getOrderById(orderId.value)
        order.value = response
        orderDetails.value = response.orderDetails || []
      } catch (error) {
        console.error('获取订单详情失败:', error)
        order.value = null
      } finally {
        loading.value = false
      }
    }
    
    const goBack = () => {
      router.push('/orders')
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '已支付',
        'SHIPPED': '已发货',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || '未知状态'
    }
    
    const getStatusClass = (status) => {
      const classMap = {
        'PENDING': 'status-pending',
        'PAID': 'status-paid',
        'SHIPPED': 'status-shipped',
        'COMPLETED': 'status-completed',
        'CANCELLED': 'status-cancelled'
      }
      return classMap[status] || 'status-unknown'
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return '未知时间'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    const handleImageError = (event) => {
      event.target.style.display = 'none'
      event.target.nextElementSibling.style.display = 'flex'
    }
    
    const payOrder = () => {
      // 跳转到支付页面
      router.push(`/checkout?orderId=${orderId.value}`)
    }
    
    const confirmReceived = async () => {
      try {
        await confirm.normal('确认收货', '确认已收到商品？')
        await orderAPI.updateOrderStatus(orderId.value, 'COMPLETED')
        order.value.orderStatus = 'COMPLETED'
        feedback.success('确认收货')
      } catch (error) {
        if (error === 'cancel') return // 用户取消
        console.error('确认收货失败:', error)
        feedback.error('确认收货')
      }
    }
    
    const cancelOrder = async () => {
      try {
        await confirm.warning('取消订单', '确定要取消这个订单吗？')
        await orderAPI.updateOrderStatus(orderId.value, 'CANCELLED')
        order.value.orderStatus = 'CANCELLED'
        feedback.success('取消订单')
      } catch (error) {
        if (error === 'cancel') return // 用户取消
        console.error('取消订单失败:', error)
        feedback.error('取消订单', '请稍后重试')
      }
    }
    
    const contactService = () => {
      showCustomerService()
    }
    
    onMounted(() => {
      if (orderId.value) {
        fetchOrderDetail()
      }
    })
    
    return {
      loading,
      order,
      orderDetails,
      goBack,
      getStatusText,
      getStatusClass,
      formatDate,
      handleImageError,
      payOrder,
      confirmReceived,
      cancelOrder,
      contactService
    }
  }
}
</script>

<style scoped>
.order-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #ffffff;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: #B0BEC5;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border-color: #00D4FF;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-header h2 i {
  color: #00D4FF;
}

.loading-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #00D4FF;
  font-size: 16px;
}

.loading-spinner i {
  font-size: 32px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.empty-icon {
  font-size: 80px;
  color: #EF4444;
  margin-bottom: 24px;
  opacity: 0.7;
}

.empty-state h3 {
  font-size: 24px;
  color: #ffffff;
  margin: 0 0 12px 0;
}

.empty-state p {
  font-size: 16px;
  color: #B0BEC5;
  margin: 0 0 32px 0;
}

.order-detail-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.order-info-card,
.shipping-info-card,
.products-card,
.order-actions-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header h3 i {
  color: #00D4FF;
}

.card-content {
  padding: 20px;
}

.order-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-pending {
  background: rgba(255, 193, 7, 0.2);
  color: #FFC107;
  border: 1px solid rgba(255, 193, 7, 0.3);
}

.status-paid {
  background: rgba(0, 212, 255, 0.2);
  color: #00D4FF;
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.status-shipped {
  background: rgba(34, 197, 94, 0.2);
  color: #22C55E;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-completed {
  background: rgba(59, 130, 246, 0.2);
  color: #3B82F6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.status-cancelled {
  background: rgba(239, 68, 68, 0.2);
  color: #EF4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.status-unknown {
  background: rgba(156, 163, 175, 0.2);
  color: #9CA3AF;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item .label {
  font-size: 14px;
  color: #B0BEC5;
  font-weight: 500;
}

.info-item .value {
  font-size: 16px;
  color: #ffffff;
  font-weight: 600;
}

.info-item .value.price {
  color: #00D4FF;
  font-size: 18px;
}

.shipping-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.recipient-info {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.recipient-name,
.recipient-phone {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #ffffff;
}

.recipient-name i,
.recipient-phone i {
  color: #00D4FF;
  width: 16px;
}

.shipping-address {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 16px;
  color: #ffffff;
  line-height: 1.5;
}

.shipping-address i {
  color: #00D4FF;
  width: 16px;
  margin-top: 2px;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-product-icon {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #00D4FF;
  background: rgba(255, 255, 255, 0.05);
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  line-height: 1.4;
}

.product-info p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #B0BEC5;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.product-meta .price {
  font-size: 16px;
  font-weight: 600;
  color: #00D4FF;
}

.product-meta .quantity {
  font-size: 14px;
  color: #B0BEC5;
}

.product-meta .subtotal {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.actions-list {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: linear-gradient(45deg, #00B8E6, #3F3BE0);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}

.btn-success {
  background: linear-gradient(45deg, #22C55E, #16A34A);
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: linear-gradient(45deg, #16A34A, #15803D);
  transform: translateY(-1px);
}

.btn-danger {
  background: linear-gradient(45deg, #EF4444, #DC2626);
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: linear-gradient(45deg, #DC2626, #B91C1C);
  transform: translateY(-1px);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #B0BEC5;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

@media (max-width: 768px) {
  .container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .recipient-info {
    flex-direction: column;
    gap: 12px;
  }
  
  .product-item {
    flex-direction: column;
    text-align: center;
  }
  
  .product-meta {
    justify-content: center;
  }
  
  .actions-list {
    justify-content: center;
  }
}
</style> 